package com.ruoyi.system.service.impl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.TreeSelect;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.system.domain.DeptFileUserDownload;
import com.ruoyi.system.domain.DeptFileUserStore;
import com.ruoyi.system.mapper.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.domain.DeptFile;
import com.ruoyi.system.service.IDeptFileService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

/**
 * 部门文件Service业务层处理
 *
 * @author ruoyi
 * @date 2024-04-16
 */
@Service
public class DeptFileServiceImpl implements IDeptFileService
{
    @Autowired
    private DeptFileMapper deptFileMapper;
    @Autowired
    private DeptFileUserStoreMapper deptFileUserStoreMapper;
    @Autowired
    private DeptFileUserDownloadMapper deptFileUserDownloadMapper;
    @Autowired
    private SysUserMapper sysUserMapper;

    /**
     * 查询部门文件
     *
     * @param fileId 部门文件主键
     * @return 部门文件
     */
    @Override
    public DeptFile selectDeptFileByFileId(Long fileId)
    {
        return deptFileMapper.selectDeptFileByFileId(fileId);
    }

    /**
     * 查询部门文件列表
     *
     * @param deptFile 部门文件
     * @return 部门文件
     */
    @Override
    public List<DeptFile> selectDeptFileList(DeptFile deptFile)
    {
        List<DeptFile> deptFiles = deptFileMapper.selectDeptFileList(deptFile);
        return deptFiles;
    }

    /**
     * 新增部门文件
     *
     * @param deptFile 部门文件
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertDeptFile(DeptFile deptFile)
    {
        // 如果父节点不为正常状态,则不允许新增子节点
        Long parentId = deptFile.getParentId();
        if(0L!= parentId){
            DeptFile deptFileByParent = deptFileMapper.selectDeptFileByFileId(deptFile.getParentId());
            if(ObjectUtils.isEmpty(deptFileByParent)){
                throw new ServiceException("文件不存在，不允许新增");
            }
            if("1".equals(deptFileByParent.getIsRecycle())||"0".equals(deptFileByParent.getDelFlag())){
                throw new ServiceException("文件不存在，不允许新增");
            }
            deptFile.setAncestors(deptFileByParent.getAncestors() + "," + deptFile.getParentId());
            deptFile.setFilePath(deptFileByParent.getFilePath()+"/"+deptFile.getFileName());
        }else {
            deptFile.setAncestors("0");
            deptFile.setFilePath("/");
        }
        deptFile.setCreateTime(DateUtils.getNowDate());
        return deptFileMapper.insertDeptFile(deptFile);
    }

    /**
     * 修改部门文件
     *
     * @param deptFileList 部门文件
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult updateDeptFile(List<DeptFile> deptFileList)
    {
        try {
            for(DeptFile deptFile : deptFileList){
                DeptFile newParentDeptFile = deptFileMapper.selectDeptFileByFileId(deptFile.getParentId());
                DeptFile oldDeptFile = deptFileMapper.selectDeptFileByFileId(deptFile.getFileId());
                if (StringUtils.isNotNull(newParentDeptFile) && StringUtils.isNotNull(oldDeptFile))
                {
                    String newAncestors = newParentDeptFile.getAncestors() + "," + newParentDeptFile.getFileId();
                    String oldAncestors = oldDeptFile.getAncestors();
                    deptFile.setAncestors(newAncestors);
                    updateDeptFileChildren(deptFile.getFileId(), newAncestors, oldAncestors);
                }
                deptFile.setUpdateTime(DateUtils.getNowDate());
                deptFileMapper.updateDeptFile(deptFile);
            }
            return AjaxResult.success("移动成功");
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("移动失败");
        }
    }

    /**
     * 复制部门文件
     *
     * @param deptFileList 部门文件
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult copyDeptFile(List<DeptFile> deptFileList){
        try {
            for(DeptFile deptFile : deptFileList){
                DeptFile newParentDeptFile = deptFileMapper.selectDeptFileByFileId(deptFile.getParentId());
                DeptFile oldDeptFile = deptFileMapper.selectDeptFileByFileId(deptFile.getFileId());
                if (StringUtils.isNotNull(newParentDeptFile) && StringUtils.isNotNull(oldDeptFile))
                {
                    String newAncestors = newParentDeptFile.getAncestors() + "," + newParentDeptFile.getFileId();
                    String oldAncestors = oldDeptFile.getAncestors();
                    deptFile.setAncestors(newAncestors);
                    insertDeptFileChildren(deptFile.getFileId(),deptFile.getParentId(), newAncestors, oldAncestors,deptFile.getCreateName());
                    DeptFile deptFile1 = new DeptFile();
                    deptFile1.setAncestors(newAncestors);
                    deptFile1.setFileName(oldDeptFile.getFileName());
                    //新的父id
                    deptFile1.setParentId(deptFile.getParentId());
                    deptFile1.setFileType(oldDeptFile.getFileType());
                    deptFile1.setFileUrl(oldDeptFile.getFileUrl());
                    deptFile1.setDeptId(oldDeptFile.getDeptId());
                    deptFile1.setFilePath(oldDeptFile.getFilePath());
                    deptFile1.setCreateTime(DateUtils.getNowDate());
                    deptFile1.setCreateBy(oldDeptFile.getCreateBy());
                    deptFile1.setCreateName(deptFile.getCreateName());
                    deptFileMapper.insertDeptFile(deptFile1);
                }else{
                    return AjaxResult.success("复制失败");
                }
            }
            return AjaxResult.success("复制成功");
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("复制失败");
        }
    }


    /**
     * 重命名
     *
     * @param deptFile 部门文件
     * @return 结果
     */
    @Override
    public int updateDeptFileName(DeptFile deptFile){
        return deptFileMapper.updateDeptFile(deptFile);
    }

    /**
     * 修改子元素关系
     *
     * @param fileId 被修改的文件ID
     * @param newAncestors 新的父ID集合
     * @param oldAncestors 旧的父ID集合
     */
    public void updateDeptFileChildren(Long fileId, String newAncestors, String oldAncestors){
        List<DeptFile> children = deptFileMapper.selectChildrenDeptFileByFileId(fileId);
        for (DeptFile child : children)
        {
            child.setAncestors(child.getAncestors().replaceFirst(oldAncestors, newAncestors));
        }
        if (children.size() > 0)
        {
            deptFileMapper.updateDeptFileChildren(children);
        }
    }


    /**
     * 复制子元素关系
     *
     * @param fileId 复制的文件ID
     * @param newAncestors 新的父ID集合
     * @param oldAncestors 旧的父ID集合
     */
    public void insertDeptFileChildren(Long fileId, Long parentId, String newAncestors, String oldAncestors,String createName){
        List<DeptFile> children = deptFileMapper.selectChildrenDeptFileByFileId(fileId);
        for (DeptFile child : children)
        {
            child.setAncestors(child.getAncestors().replaceFirst(oldAncestors, newAncestors));
            DeptFile deptFile = new DeptFile();
            deptFile.setDeptId(child.getDeptId());
            deptFile.setFileName(child.getFileName());
            deptFile.setFileUrl(child.getFileUrl());
            deptFile.setFileType(child.getFileType());
            deptFile.setFilePath(child.getFilePath());
            deptFile.setCreateTime(DateUtils.getNowDate());
            deptFile.setCreateBy(child.getCreateBy());
            deptFile.setParentId(child.getParentId());
            deptFile.setAncestors(child.getAncestors());
            deptFile.setCreateName(createName);
            deptFileMapper.insertDeptFile(deptFile);
        }
    }

    /**
     * 删除部门文件信息
     *
     * @param fileId 部门文件主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteDeptFileByFileId(Long fileId)
    {
        List<DeptFile> deptFiles = deptFileMapper.selectChildrenDeptFileByFileId(fileId);
        for(DeptFile file :deptFiles ){
            deptFileMapper.deleteDeptFileByFileId(file.getFileId());
        }
        return deptFileMapper.deleteDeptFileByFileId(fileId);
    }

    /**
     * 放入回收站
     *
     * @param deptFile 部门文件主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int recycleDeptFile(DeptFile deptFile){
        List<DeptFile> deptFiles = deptFileMapper.selectChildrenDeptFileByFileId(deptFile.getFileId());
        for(DeptFile file :deptFiles ){
            DeptFile deptFileVo = new DeptFile();
            deptFileVo.setFileId(file.getFileId());
            deptFileVo.setIsRecycle(deptFile.getIsRecycle());
            deptFileMapper.updateDeptFile(deptFileVo);
        }
        return deptFileMapper.updateDeptFile(deptFile);
    }



    /**
     * 收藏
     *
     * @param deptFile 部门文件主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult storeDeptFile(DeptFile deptFile){
        List<Long> fileIdList = deptFile.getFileIdList();
        try {
            for(Long fileId : fileIdList){
                DeptFile deptFileVo = new DeptFile();
                deptFileVo.setFileId(fileId);
                List<DeptFile> deptFiles = deptFileMapper.selectChildrenDeptFileByFileId(fileId);
                for(DeptFile file :deptFiles ){
                    DeptFileUserStore deptFileUserStore = new DeptFileUserStore();
                    deptFileUserStore.setFileId(file.getFileId());
                    deptFileUserStore.setUserId(deptFile.getUserId());
                    deptFileUserStoreMapper.insertDeptFileUserStore(deptFileUserStore);
                }
                DeptFileUserStore deptFileUserStore = new DeptFileUserStore();
                deptFileUserStore.setFileId(fileId);
                deptFileUserStore.setUserId(deptFile.getUserId());
                deptFileUserStoreMapper.insertDeptFileUserStore(deptFileUserStore);
            }
            return AjaxResult.success("收藏成功");
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("收藏失败");
        }
    }

    /**
     * 下载
     *
     * @param deptFile 部门文件主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult downloadFile(DeptFile deptFile){
        List<Long> fileIdList = deptFile.getFileIdList();
        try {
            for(Long fileId : fileIdList){
                deptFile.setFileId(fileId);
                //添加到下载列表
                List<DeptFile> deptFiles = deptFileMapper.selectChildrenDeptFileByFileId(fileId);
                for(DeptFile file :deptFiles ){
                    DeptFileUserDownload deptFileUserDownload = new DeptFileUserDownload();
                    deptFileUserDownload.setFileId(file.getFileId());
                    deptFileUserDownload.setUserId(deptFile.getUserId());
                    deptFileUserDownload.setCreateBy(deptFile.getCreateBy());
                    deptFileUserDownload.setCreateName(deptFile.getCreateName());
                    deptFileUserDownloadMapper.insertDeptFileUserDownload(deptFileUserDownload);
                }
                DeptFileUserDownload deptFileUserDownload = new DeptFileUserDownload();
                deptFileUserDownload.setFileId(fileId);
                deptFileUserDownload.setUserId(deptFile.getUserId());
                deptFileUserDownload.setCreateBy(deptFile.getCreateBy());
                deptFileUserDownload.setCreateName(deptFile.getCreateName());
                deptFileUserDownloadMapper.insertDeptFileUserDownload(deptFileUserDownload);
            }
            return AjaxResult.success("下载成功");
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.success("下载失败");
        }
    }

    public List<DeptFile> buildDeptTree(List<DeptFile> depts)
    {
        List<DeptFile> returnList = new ArrayList<DeptFile>();
        List<Long> tempList = depts.stream().map(DeptFile::getFileId).collect(Collectors.toList());
        for (DeptFile deptFile : depts)
        {
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(deptFile.getParentId()))
            {
                recursionFn(depts, deptFile);
                returnList.add(deptFile);
            }
        }
        if (returnList.isEmpty())
        {
            returnList = depts;
        }
        return returnList;
    }

    /**
     * 递归列表
     */
    private void recursionFn(List<DeptFile> list, DeptFile t)
    {
        // 得到子节点列表
        List<DeptFile> childList = getChildList(list, t);
        t.setChildren(childList);
        for (DeptFile tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }


    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<DeptFile> list, DeptFile t)
    {
        return getChildList(list, t).size() > 0;
    }

    /**
     * 得到子节点列表
     */
    private List<DeptFile> getChildList(List<DeptFile> list, DeptFile t)
    {
        List<DeptFile> tlist = new ArrayList<DeptFile>();
        Iterator<DeptFile> it = list.iterator();
        while (it.hasNext())
        {
            DeptFile n = (DeptFile) it.next();
            if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().longValue() == t.getFileId().longValue())
            {
                tlist.add(n);
            }
        }
        return tlist;
    }


    /**
     * 校验文件名称是否唯一
     *
     * @param deptFile 党组织信息
     * @return 结果
     */
    @Override
    public boolean checkDeptFileNameUnique(DeptFile deptFile){
        Long fileId = StringUtils.isNull(deptFile.getFileId()) ? -1L : deptFile.getFileId();
        DeptFile info = deptFileMapper.checkFileNameUnique(deptFile.getFileName(), deptFile.getParentId());
        if (StringUtils.isNotNull(info) && info.getFileId().longValue() != fileId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }


    /**
     * 根据ID查询所有子文件
     *
     * @param fileId 文件ID
     * @return 文件列表
     */
    @Override
    public List<DeptFile> selectChildrenDeptFileByFileId(Long fileId){
        List<DeptFile> deptFiles = deptFileMapper.selectChildrenDeptFileByFileId(fileId);
        return deptFiles;
    }


}
